package cn.bdqn.hospital.utils;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 封装jdbc的开、关连接的功能
 */
public class JDBCUtils {
    private static String driver;
    private static String url;
    private static String username;
    private static String password;
    static{
        // 加载配置文件
        Properties properties = new Properties();
        try {
            properties.load(JDBCUtils.class.getClassLoader()
                    .getResourceAsStream("database.properties"));
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 加载驱动
        try {
            Class.forName(driver);
            System.out.println("驱动加载成功！");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    /**
     * 获得连接
     * @return
     */
    public static Connection getConnection(){
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url,username,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    /**
     * 关闭连接
     * @param connection
     * frtv
     */
    public static void close(Connection connection){
        try {
            if(connection != null)connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
